
/**
 * 多种校验方法
 */
import Vue from 'vue'

var Func = function() {
	for (var fn in this) {
		if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {
			this[fn] = this[fn].bind(this);
		}
	}
};


Func.prototype.urlEncode = function(params) {
	if (this.isEmptyObject(params)) {
		return '';
	}
	
	let pars = '';
	for(let k in params) {
		if (typeof params[k] == 'object') {
			pars += '&'+k+'='+encodeURIComponent(JSON.stringify(params[k]))
		} else {
			pars += '&'+k+'='+encodeURIComponent(params[k])
		}
	}
	
	return '?'+pars.substr(1);
};

//生成uuid
Func.prototype.guid = function() {
	return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
		var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
		return v.toString(16);
	});
};

//校验是否为数字
Func.prototype.isNumber = function(val){
	var regPos = /^\d+(\.\d+)?$/; //非负浮点数
	var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
	if(regPos.test(val) || regNeg.test(val)){
		return true;
	}else{
		return false;
	}
};
 //小数点后保留两位,返回时是string类型
 Func.prototype.Float = function (value) {
    var value = Math.round(parseFloat(value) * 100) / 100;
    var xsd = value.toString().split(".");
    if (xsd.length == 1) {
      value = value.toString() + ".00";
      return value;
    }
    if (xsd.length > 1) {
      if (xsd[1].length < 2) {
        value = value.toString() + "0";
      }
      return value;
    }
},

//  输出：大于0的两位小数Positive decimal
Func.prototype.PosDecimal2 = function(val){
	var	newVal = val.replace(/[^\d.]/g,"");  //清除“数字”和“.”以外的字符   
	newVal = newVal.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的   
	newVal = newVal.replace(".","$#$").replace(/\./g,"").replace("$#$",".");  
	newVal = newVal.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能输入两个小数   
  	if (newVal.indexOf(".") >= 0) {
	var index = newVal.indexOf(".");
		if (newVal.slice(index + 1, newVal.length).length > 2) {
			newVal = newVal.slice(0, index + 3);
			return;
		}
	}
	if(newVal.indexOf(".")< 0 && newVal !=""){//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额  
		newVal = parseFloat(newVal).toString();
	} 
//newVal返回是string类型
  return newVal;
};
//  输出：大于0的一位小数 
Func.prototype.PosDecimal1 = function(val) {
	var	newVal = val.replace(/[^\d.]/g,""); 
	newVal = newVal.replace(/\.{2,}/g,".");   
	newVal = newVal.replace(".","$#$").replace(/\./g,"").replace("$#$",".");

	if ( newVal.indexOf(".") >= 0) {
		var index = newVal.indexOf(".");
		if (newVal.slice(index + 1, newVal.length).length > 1) {
		   newVal = newVal.slice(0, index + 2);
		}
	}

	if(newVal.indexOf(".")< 0 && newVal !=""){ 
		newVal = parseFloat(newVal).toString();
	} 

	return newVal;
};

//校验是否为日期
Func.prototype.isDate = function(s) {
	var reg = /^\d{4}-\d{2}-\d{2}$|^\d{4}-\d{2}-\d{2} \d{1,2}:\d{1,2}:\d{1,2}$|\d{1,2}:\d{1,2}:\d{1,2}$/;
	return reg.exec(s);
};

//校验是否为邮箱
Func.prototype.isEmail = function(s) {
	var reg = /^[a-z0-9]([a-z0-9_\-\.]*)@([a-z0-9_\-\.]*)(\.[a-z]{2,3}(\.[a-z]{2}){0,2})$/i;
	return reg.exec(s);
};

//校验是否为整数
Func.prototype.isDigital = function(s) {
	var reg = /^\d+$/;
	return reg.exec(s);
};

//校验是否为手机
Func.prototype.isMobile = function(s) {
	var reg =/^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[3-8]{1})|(18[0-9]{1})|(19[0-9]{1})|(14[5-7]{1}))+\d{8})$/;
	return reg.exec(s);
};

//校验是否为电话
Func.prototype.isPhone = function(s) {
	var reg = /^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,6})?$/;
	return reg.exec(s);
};

//校验是否为身份证
Func.prototype.isIdentity = function( s ) {
	var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
	return reg.exec(s);
};

//校验是否为网址
Func.prototype.isWebAddress = function(s) {
	return /^((https|http|ftp|rtsp|mms){0,1}(:\/\/){0,1})www\.(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$/i.test(s);
};

//校验是否为邮编
Func.prototype.isPostcode = function(s) {
	return  /^[1-9][0-9]{5}$/.test(s);
};

//是否为全中文
Func.prototype.hasFullChinese = function(s) {
	return  /^[\u4e00-\u9fa5]+$/u.test(s);
};

//是否包含中文
Func.prototype.hasChinese = function(s) {
	return  /[\u4e00-\u9fa5]/u.test(s);
};

/**
 * 深度拷贝
 * @param obj
 * @returns {*}
 */
Func.prototype.deepClone = function(obj){
	var objClone = Array.isArray(obj)?[]:{};
	if(obj && typeof obj==="object"){
		for(var key in obj){
			if(obj.hasOwnProperty(key)){
				//判断ojb子元素是否为对象，如果是，递归复制
				if(obj[key]&&typeof obj[key] ==="object"){
					objClone[key] = this.deepClone(obj[key]);
				}else{
					//如果不是，简单复制
					objClone[key] = obj[key];
				}
			}
		}
	}
	return objClone;
};

/**
 * 对象的合成
 * @param dst 原始对象
 * @param src 参数对象
 * @returns {*}
 * @private
 */
Func.prototype.extend = function(dst, src) {
	if (dst && src) {
		for (var key in src) {
			if (!dst.hasOwnProperty(key)) {
				dst[key] = src[key];
			}
		}
	}
	return dst;
};

/**
 * 纯Json对象的拷贝（兑现中不包含函数）
 * @param obj
 * @returns {*}
 */
Func.prototype.jsonCopy = function(obj) {
	return JSON.parse(JSON.stringify(obj)); 
};

/**
 * 从字符串的两端删除空白字符和其他预定义字符
 * @param s
 * @returns {*}
 */
Func.prototype.trim = function(s) {
	return s.replace(/(^\s*)|(\s*$)/g, '');
};

//判断值是否为空
Func.prototype.isEmpty = function (val) {
	switch (typeof(val)){
		case "string":
			return this.trim(val).length == 0 ? true : false;
			break;
		case "number":
			return val == 0;
			break;
		case "object":
			return val == null;
			break;
		case "array":
			return val.length == 0;
			break;
		case "undefined":
			return true;
			break;
		default:
			return true;
	}
};

/**
 * 匹配密码
 */
Func.prototype.isPwd = function( s ) {
	var reg = /^[A-Za-z0-9_-]{6,30}$/;
	return reg.exec(s);
};

/**
 * 判断是否为空对象
 * console.log(this.$F.isEmptyObject(''),'==true==isEmptyObject===')
 * @param obj
 * @returns {boolean}
 */
Func.prototype.isEmptyObject = function(obj){
	switch ( typeof obj){
		case 'undefined':
			return true;
			break;
		case 'object':
			var fy = JSON.stringify(obj);
			if( fy=='{}' || fy=='[]' || fy=='null' ){
				return true;
			}
			break;
		default:
			return true;
	}
	return false;
};

/*
 * JS排序
 */
Func.prototype.key_sort = function(resource){
	var sdic = Object.keys(resource).sort();
	var new_obj = {};
	for(var ki in sdic){
		new_obj[sdic[ki]] = resource[sdic[ki]];
	}
	return new_obj;
};

Func.prototype.val_sort = function(resource,val_key,type){
	var type = type || 1;
	var tempObj = this.jsonCopy(resource);

	for (var k in tempObj) {
		tempObj[k]['F_SORT_KEY'] = k;
	}

	if( type == 1 ){ //按值升序
		var sdic = Object.keys(tempObj).sort(function(a,b){return tempObj[a][val_key] - tempObj[b][val_key]});
	} else { //按值降序
		var sdic = Object.keys(tempObj).sort(function(a,b){return tempObj[a][val_key] < tempObj[b][val_key]});
	}

	var new_obj = [];
	for(var ki in sdic){
		new_obj.push(tempObj[sdic[ki]]);
	}
	return new_obj;
};

//浏览器相关操作
Func.prototype.findDimensions = function(){

	//获取窗口宽度
	if (window.innerWidth){
		var  winWidth = window.innerWidth;
	} else if ((document.body) && (document.body.clientWidth)){
		var winWidth = document.body.clientWidth;
	}

	//获取窗口高度
	if (window.innerHeight){
		var winHeight = window.innerHeight;
	}else if ((document.body) && (document.body.clientHeight)){
		var winHeight = document.body.clientHeight;
	}

	//通过深入Document内部对body进行检测，获取窗口大小
	if (document.documentElement  && document.documentElement.clientHeight && document.documentElement.clientWidth){
		winHeight = document.documentElement.clientHeight;
		winWidth = document.documentElement.clientWidth;
	}

	return {
		winWidth : winWidth,
		winHeight : winHeight
	};

};

const F = new Func();
export default F;